<template>
    <div class="course-bg">
        <div class="course-container">
            <div class="header-bar">
                <h2>课程管理</h2>
                <div>
                    <el-input v-model="searchKeyword" placeholder="搜索课程名称" style="width: 200px; margin-right: 10px;"
                        clearable />
                    <el-button type="primary" @click="addDialogVisible = true">新增课程</el-button>
                </div>
            </div>
            <el-table :data="filteredCourses" style="width: 100%; margin-top: 20px;">
                <el-table-column prop="courseId" label="课程编号" width="120" />
                <el-table-column prop="courseName" label="课程名称" />
                <el-table-column prop="credit" label="学分" width="100" />
                <el-table-column label="操作" width="180">
                    <template #default="scope">
                        <el-button size="small" type="primary" @click="editCourse(scope.row)">编辑</el-button>
                        <el-button size="small" type="danger" @click="confirmDeleteCourse(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 新增课程弹窗 -->
            <el-dialog v-model="addDialogVisible" title="新增课程" width="350px">
                <el-form :model="addForm">
                    <el-form-item label="课程名称">
                        <el-input v-model="addForm.courseName" />
                    </el-form-item>
                    <el-form-item label="学分">
                        <el-input v-model.number="addForm.credit" type="number" min="1" max="10" />
                    </el-form-item>
                </el-form>
                <template #footer>
                    <el-button @click="addDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitAddCourse">添加</el-button>
                </template>
            </el-dialog>

            <!-- 编辑课程弹窗 -->
            <el-dialog v-model="editDialogVisible" title="编辑课程" width="350px">
                <el-form :model="editForm">
                    <el-form-item label="课程名称">
                        <el-input v-model="editForm.courseName" />
                    </el-form-item>
                    <el-form-item label="学分">
                        <el-input v-model.number="editForm.credit" type="number" min="1" max="10" />
                    </el-form-item>
                </el-form>
                <template #footer>
                    <el-button @click="editDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitEditCourse">保存</el-button>
                </template>
            </el-dialog>

            <!-- 删除确认弹窗 -->
            <el-dialog v-model="deleteDialogVisible" title="删除课程" width="300px">
                <span>确定要删除 <b>{{ deleteTarget.courseName }}</b> 吗？</span>
                <template #footer>
                    <el-button @click="deleteDialogVisible = false">取消</el-button>
                    <el-button type="danger" @click="submitDeleteCourse">删除</el-button>
                </template>
            </el-dialog>
        </div>
    </div>
    <BottomNav />
</template>

<script setup>
import BottomNav from '../components/BottomNav.vue'
import { ref, computed, onMounted } from 'vue'
import { useUserStore } from '../store/user'
import axios from 'axios'

const userStore = useUserStore()
const courses = ref([])
const searchKeyword = ref('')

// 弹窗相关
const addDialogVisible = ref(false)
const editDialogVisible = ref(false)
const deleteDialogVisible = ref(false)

// 表单相关
const addForm = ref({ courseName: '', credit: 1 })
const editForm = ref({})
const deleteTarget = ref({})

// 过滤课程
const filteredCourses = computed(() => {
    if (!searchKeyword.value) return courses.value
    return courses.value.filter(item =>
        item.courseName.includes(searchKeyword.value)
    )
})

// 获取课程列表
const fetchCourses = async () => {
    try {
        const teacherId = userStore.teacherId || localStorage.getItem('teacherId')
        const res = await axios.get('/api/teacher/courses', { params: { teacherId } })
        console.log(res)
        if (res.data.code === 200) {
            courses.value = res.data.data
        } else {
            courses.value = []
            alert(res.data.msg || '查询失败')
        }
    } catch (e) {
        courses.value = []
        alert('网络错误，请稍后重试')
    }
}

// 新增课程
const submitAddCourse = async () => {
    if (!addForm.value.courseName.trim()) {
        return alert('课程名称不能为空')
    }
    try {
        const teacherId = userStore.teacherId || localStorage.getItem('teacherId')
        const res = await axios.post('/api/teacher/add-course', {
            teacherId,
            courseName: addForm.value.courseName.trim(),
            credit: addForm.value.credit
        })
        if (res.data.code === 200) {
            addDialogVisible.value = false
            addForm.value = { courseName: '', credit: 1 }
            fetchCourses()
            alert('课程添加成功')
        } else {
            alert(res.data.msg || '添加失败')
        }
    } catch (e) {
        alert('网络错误，添加失败')
    }
}

// 编辑课程
const editCourse = (row) => {
    editForm.value = { ...row }
    editDialogVisible.value = true
}
const submitEditCourse = async () => {
    if (!editForm.value.courseName.trim()) {
        return alert('课程名称不能为空')
    }
    try {
        const teacherId = userStore.teacherId || localStorage.getItem('teacherId')
        const res = await axios.put('/api/teacher/update-course', {
            teacherId,
            courseId: editForm.value.courseId,
            courseName: editForm.value.courseName.trim(),
            credit: editForm.value.credit
        })
        if (res.data.code === 200) {
            editDialogVisible.value = false
            fetchCourses()
            alert('课程修改成功')
        } else {
            alert(res.data.msg || '修改失败')
        }
    } catch (e) {
        alert('网络错误，修改失败')
    }
}

// 删除课程
const confirmDeleteCourse = (row) => {
    deleteTarget.value = { ...row }
    deleteDialogVisible.value = true
}
const submitDeleteCourse = async () => {
    try {
        const teacherId = userStore.teacherId || localStorage.getItem('teacherId')
        const res = await axios.delete('/api/teacher/delete-course', {
            data: {
                teacherId,
                courseId: deleteTarget.value.courseId
            }
        })
        if (res.data.code === 200) {
            deleteDialogVisible.value = false
            fetchCourses()
            alert('课程删除成功')
        } else {
            alert(res.data.msg || '删除失败')
        }
    } catch (e) {
        alert('网络错误，删除失败')
    }
}

onMounted(() => {
    fetchCourses()
})
</script>

<style scoped>
.course-bg {
    min-height: 100vh;
    width: 100vw;
    position: relative;
    background: linear-gradient(120deg, #a1c4fd 0%, #c2e9fb 100%);
    display: flex;
    align-items: flex-start;
    justify-content: center;
    padding-top: 40px;
    overflow-x: hidden;
}

.course-container {
    position: relative;
    z-index: 1;
    background: rgba(255, 255, 255, 0.98);
    border-radius: 22px;
    box-shadow: 0 8px 32px 0 rgba(80, 120, 200, 0.10);
    padding: 38px 32px 32px 32px;
    min-width: 340px;
    max-width: 900px;
    width: 100%;
    margin-bottom: 40px;
    margin-top: 0;
    transition: box-shadow 0.2s;
}

.header-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
}
</style>